﻿using Cjj.Exam.Entities;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.AuditLogging.EntityFrameworkCore;
using Volo.Abp.BackgroundJobs.EntityFrameworkCore;
using Volo.Abp.Data;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.Modeling;

namespace Cjj.Exam.EntityFrameworkCore;

[ConnectionStringName("Default")]
public class ExamDbContext :
    AbpDbContext<ExamDbContext>
    //IIdentityDbContext,
    //ITenantManagementDbContext
{
    /* Add DbSet properties for your Aggregate Roots / Entities here. */

    #region Entities from the modules


    #endregion

    public DbSet<CjjBook> CjjBooks { get; set; }
    public DbSet<Author> Authors { get; set; }

    public ExamDbContext(DbContextOptions<ExamDbContext> options)
        : base(options)
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.ConfigureBackgroundJobs();
        builder.ConfigureAuditLogging();

        builder.Entity<CjjBook>(b =>
        {
            b.ToTable(ExamConsts.DbTablePrefix + "Books", ExamConsts.DbSchema);
            b.ConfigureByConvention(); //auto configure for the base class props
            b.Property(x => x.Name).IsRequired().HasMaxLength(128);

            b.HasOne<Author>().WithMany().HasForeignKey(x => x.AuthorId).IsRequired();
        });

        builder.Entity<Author>(b =>
        {
            b.ToTable(ExamConsts.DbTablePrefix + "Authors",
                ExamConsts.DbSchema);

            b.ConfigureByConvention();

            b.Property(x => x.Name)
                .IsRequired()
                .HasMaxLength(AuthorConsts.MaxNameLength);

            b.HasIndex(x => x.Name);
        });
    }
}
